﻿using EMoney.IStock.Client.Models;
using EMoney.IStock.Client.Models.API;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EMoney.IStock.Client.Framework
{
    public class ClientTokenHelper
    {
        private const string RIGHT_MEMCACHED_KEY = "EMoney.IStock.Client.Framework.Right";

        ServiceStack.Redis.RedisClient redisClient = new ServiceStack.Redis.RedisClient(ConfigHelper.ClientRedis);

        /// <summary>
        /// 获取用户预警信息
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public static string GetAlarmsSetting(int userid)
        {
            ClientTokenHelper clientToken = new ClientTokenHelper();

            return clientToken.GetHash(string.Concat(userid, ":data"), "key_alarms_setting");
        }

        /// <summary>
        /// 获取自选股
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public static string GetZxg(int userid)
        {
            return CacheManager.ClientCache.Get<string>(string.Concat(userid, ":stock:."));
        }

        /// <summary>
        /// 通过临时token获取(同时支持真实token获取)
        /// </summary>
        /// <param name="r_token"></param>
        /// <returns></returns>
        public static string GetUserIdByToken(string r_token)
        {
            if (string.IsNullOrEmpty(r_token))
            {
                return string.Empty;
            }

            bool bTempToken = true;

            ClientTokenHelper clientToken = new ClientTokenHelper();

            // 从临时token中寻找永久token
            string strLongToken = clientToken.GetHash("tradeids", r_token);

            if (string.IsNullOrEmpty(strLongToken))
            {
                strLongToken = r_token;
                bTempToken = false;
            }

            string userID = clientToken.GetHash("token_id", strLongToken);

            if (bTempToken)
            {
                try
                {
                    clientToken.deleHash("tradeids", r_token);

                    strLongToken += ":trade";
                    clientToken.deleHash(strLongToken, r_token);
                }
                catch //(Exception e) 
                { }
            }

            return userID;
        }

        /// <summary>
        /// 获取用户权限
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public static List<KeyValue> GetUserRights(string userid)
        {
            if (string.IsNullOrEmpty(userid))
            {
                return null;
            }
            else
            {
                ClientTokenHelper clientToken = new ClientTokenHelper();
                
                string hashname = string.Concat(userid, ":right");
                List<KeyValue> list = clientToken.GetHashAll(hashname);

                if (list != null && list.Count > 0)
                {
                    System.DateTime time = System.DateTime.MinValue;
                    System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));

                    foreach (KeyValue r in list)
                    {
                        try
                        {
                            r.value = startTime.AddSeconds(Convert.ToDouble(r.value)).ToString("yyyy-MM-dd HH:mm:ss");
                        }
                        catch
                        {
                        }                        
                    }
                }

                return list;
            }
        }

        /// <summary>
        /// 检查用户权限
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="rightKey"></param>
        /// <returns></returns>
        public static bool CheckUserRight(string userid,string rightKey)
        {
            if (string.IsNullOrEmpty(userid) || string.IsNullOrEmpty(rightKey))
            {
                return false;
            }

            //string key = string.Concat(RIGHT_MEMCACHED_KEY, ".", userid, ".", StringHelper.FormatDateTime(DateTime.Now));

            List<KeyValue> list = GetUserRights(userid); //CacheManager.DefaultCache.Get<List<KeyValue>>(key);
            
            //if (list == null)
            //{
            //    list = GetUserRights(userid);

            //    if (list == null)
            //    {
            //        list = new List<KeyValue>();
            //    }
                
            //    CacheManager.DefaultCache.Set<List<KeyValue>>(key, list, 60 * 8);
            //}

            if (list != null && list.Count > 0)
            {
                KeyValue rights = list.Find(lst => lst.key == rightKey);

                if (rights != null && Convert.ToDateTime(rights.value) >= DateTime.Now)
                {
                    return true;
                }
            }

            return false;
        }

        private static string GetEncryptKey(string sUrl)
        {
            Uri uri;
            if (!Uri.TryCreate(sUrl, UriKind.RelativeOrAbsolute, out uri))
            {
                return sUrl;
            }

            List<string> list = new List<string>();
            string queryStr = uri.Query;
            if (queryStr.IndexOf("?") == 0)
            {
                queryStr = queryStr.Substring(1);
            }
            string[] querys = queryStr.Split('&');
            foreach (string q in querys)
            {
                list.Add(q);
            }
            list.Sort();
            list.Sort();
            StringBuilder sBuilder = new StringBuilder();
            foreach (string q in list)
            {
                sBuilder.Append(q);
            }
            string toEncrypt = sBuilder.ToString() + ConfigHelper.Key;
            string md5New = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(toEncrypt, "md5");
            return md5New;
        }

        public string GetHash(string hashname, string key)
        {
            try
            {
                byte[] b_key = System.Text.Encoding.UTF8.GetBytes(key);
                byte[] content = redisClient.HGet(hashname, b_key);
                if (content != null)
                    return Encoding.GetEncoding("utf-8").GetString(content);
                else
                    return null;
            }
            catch (Exception e)
            {
                return string.Empty;
            }
        }

        public List<KeyValue> GetHashAll(string hashname)
        {
            ArrayList box = new ArrayList();
            List<KeyValue> list = new List<KeyValue>();
            try
            {
                byte[][] b = redisClient.HGetAll(hashname);// redisClient.HGetAll_GBK(hashname);
                int c = b.Count();
                for (int i = 0; i <= c - 1; i++)
                {
                    string val = Encoding.GetEncoding("utf-8").GetString(b[i]);
                    box.Add(val);

                    KeyValue ha = new KeyValue();
                    ha.key = val;
                    ha.value = Encoding.GetEncoding("utf-8").GetString(b[i + 1]);
                    i += 1;
                    list.Add(ha);
                }
                return list;
            }
            catch (Exception e)
            {
                return new List<KeyValue>();
            }
        }

        public void deleHash(string hashname, string key)
        {
            byte[] b_key = System.Text.Encoding.UTF8.GetBytes(key);
            redisClient.HDel(hashname, b_key);
        }
    }
}
